<template>
  <div class="app-container home">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="12" :lg="8">
        <el-card class="update-log">
          <div slot="header" class="clearfix">
            <span>主控板配置</span>
          </div>
          <div class="body">
         
            <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
              <el-form-item v-if="false" label="编号" prop="id">
              <el-input v-model="formData.id" value="1" />
            </el-form-item>
      <el-form-item label="MAC地址" prop="mac">
        <!-- <el-input v-model="formData.mac" placeholder="请输入MAC地址" clearable :style="{width: '100%'}">
        </el-input> -->
        {{ formData.mac }}
      </el-form-item>
      <el-form-item label="IP地址" prop="ip">
        <el-input v-model="formData.ip" placeholder="请输入IP地址" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="子网掩码" prop="subnetMask">
        <el-input v-model="formData.subnetMask" placeholder="请输入子网掩码" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="网关地址" prop="gateway">
        <el-input v-model="formData.gateway" placeholder="请输入网关地址" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item size="large">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">取消</el-button>
      </el-form-item>
    </el-form>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12" :lg="8">
        <el-card class="update-log">
          <div slot="header" class="clearfix">
            <span>直播板卡1</span>
          </div>
          <div class="body">
            <el-form ref="elForm1" :model="formData1" :rules="rules" size="medium" label-width="100px">
      <el-form-item label="MAC地址" prop="mac">
        <!-- <el-input v-model="formData1.mac" placeholder="请输入MAC地址" clearable :style="{width: '100%'}">
        </el-input> -->
        {{ formData1.mac }}
      </el-form-item>
      <el-form-item label="IP地址" prop="ip">
        <el-input v-model="formData1.ip" placeholder="请输入IP地址" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="子网掩码" prop="subnetMask">
        <el-input v-model="formData1.subnetMask" placeholder="请输入子网掩码" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="网关地址" prop="gateway">
        <el-input v-model="formData1.gateway" placeholder="请输入网关地址" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item size="large">
        <el-button type="primary" @click="submitForm1">提交</el-button>
        <el-button @click="resetForm1">取消</el-button>
      </el-form-item>
    </el-form>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12" :lg="8">
        <el-card class="update-log">
          <div slot="header" class="clearfix">
            <span>直播板卡2</span>
          </div>
          <div class="body">
            <el-form ref="elForm2" :model="formData2" :rules="rules" size="medium" label-width="100px">
      <el-form-item label="MAC地址" prop="mac">
        {{ formData2.mac }}
      </el-form-item>
   
      <el-form-item label="IP地址" prop="ip">
        <el-input v-model="formData2.ip" placeholder="请输入IP地址" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="子网掩码" prop="subnetMask">
        <el-input v-model="formData2.subnetMask" placeholder="请输入子网掩码" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="网关地址" prop="gateway">
        <el-input v-model="formData2.gateway" placeholder="请输入网关地址" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item size="large">
        <el-button type="primary" @click="submitForm2">提交</el-button>
        <el-button @click="resetForm2">取消</el-button>
      </el-form-item>
    </el-form>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>

import { listNetwork, getChannel, delChannel, addChannel, updateNetwork,listSqlNetwork } from "@/api/system/network";

export default {
  components: {},
  props: [],
  name: "Index",
  data() {
    return {
      loadingInstance: null,
      changeFlag:true,
      changeFlag1:true,
      changeFlag2:true,
      version: "3.8.9",
      formData: {
        mac: undefined,
        ip: undefined,
        subnetMask: undefined,
        gateway: undefined,
      },
      formData1: {
        mac: undefined,
        ip: undefined,
        subnetMask: undefined,
        gateway: undefined,
      },
      formData2: {
        mac: undefined,
        ip: undefined,
        subnetMask: undefined,
        gateway: undefined,
      },
      rules: {
        gateway: [
          { required: true, message: "网关地址不能为空", trigger: "blur" },
          { validator: this.validateIp, message: '请输入正确的网关地址', trigger: 'blur' }
        ],
        subnetMask: [
          { required: true, message: "子网掩码不能为空", trigger: "blur" },
          { validator: this.validateSubnetMask, message: '请输入正确的子网掩码', trigger: 'blur' }
        ],
        ip: [
            { required: true, message: "IP地址不能为空", trigger: "blur" },
            { validator: this.validateIp, message: '请输入正确的IP地址', trigger: 'blur' }
        ],
      },
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getListTotal();
  },
  mounted() {},
  methods: {


    validateIp(rule, value, callback) {
      const ipReg = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
      if (!ipReg.test(value)) {
        callback(new Error('请输入正确的 IP 地址'));
      } else {
        callback();
      }
    },
    validateSubnetMask(rule, value, callback) {
      const ipReg = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
      if (!ipReg.test(value)) {
        callback(new Error('请输入正确格式的子网掩码'));
        return;
      }
      const parts = value.split('.');
      let binaryStr = '';
      for (const part of parts) {
        binaryStr += parseInt(part).toString(2).padStart(8, '0');
      }
      const firstZeroIndex = binaryStr.indexOf('0');
      if (firstZeroIndex === -1) {
        callback();
        return;
      }
      const remainingStr = binaryStr.slice(firstZeroIndex);
      if (remainingStr.includes('1')) {
        callback(new Error('请输入正确的子网掩码'));
      } else {
        callback();
      }
    },

    getListTotal() {


      // 1. 发起请求前：显示全局弹框，提示“正在等待后端响应，请等待”
      this.loadingInstance = this.$loading({
        lock: true, // 锁定屏幕滚动
        text: '正在获取主控板和直播板卡网络配置，请等待', // 弹框提示文本
        spinner: 'el-icon-loading', // 加载图标（Element UI 内置）
        background: 'rgba(0, 0, 0, 0.7)' // 背景遮罩（半透明黑色，增强视觉层级）
      });



      this.loading = true;
      listNetwork().then(response => {
        console.log("获取到的网络数据:"+JSON.stringify(response));
        this.formData = response.data.sysNetwork;
        this.formData1 = response.data.sysNetwork1;
        this.formData2 = response.data.sysNetwork2;
        this.changeFlag = response.data.pingNetworkChange;
        this.changeFlag1 = response.data.pingNetworkChange1;
        this.changeFlag2 = response.data.pingNetworkChange2;
        console.log("============="+this.changeFlag+"========="+this.changeFlag1+"=========="+this.changeFlag2);
        if(!this.changeFlag){
          this.$modal.alertError("服务器获取地址异常,暂时不允许网络配置");
        }
        if(!this.changeFlag1){
          this.$modal.alertError("直播板卡1网络连接异常,暂时不允许修改该网络地址");
        }
        if(!this.changeFlag2){
          this.$modal.alertError("直播板卡2网络连接异常,暂时不允许修改该网络地址");
        }

        this.loading = false;
        console.log("获取到的网络数据:"+JSON.stringify(this.formData));
        console.log("获取到的网络数据:"+JSON.stringify(this.formData1));
        console.log("获取到的网络数据:"+JSON.stringify(this.formData2));
      })
      .catch(error => {
        // 4. 请求失败：提示错误信息（新增，避免用户无感知）
        this.$modal.alertError("后端获取网络配置数据失败，请稍后重试");
        console.error("获取网络数据报错：", error); // 控制台打印错误，便于调试
      })
      .finally(() => {
        // 5. 无论成功/失败：关闭弹框（关键！确保弹框必关）
        this.loadingInstance.close();
        // 重置 loading 实例（避免内存泄漏）
        this.loadingInstance = null;
      });
    },
    getList() {

        this.loadingInstance = this.$loading({
        lock: true,
        text: '正在加载主控版网络配置数据，请等待',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });


      this.loading = true;
      listSqlNetwork().then(response => {
        this.formData = response.data.sysNetwork;
        this.loading = false;
      })
       .catch(error => {
        this.$modal.alertError("加载主控版网络配置数据失败，请稍后重试");
        console.error("getList 报错：", error);
      })
      .finally(() => {
        // 关闭弹框
        this.loadingInstance.close();
        this.loadingInstance = null;
      });
    },
    getList1() {

      this.loadingInstance = this.$loading({
        lock: true,
        text: '正在加载直播板卡1网络配置数据，请等待',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      this.loading = true;
      listSqlNetwork().then(response => {
        this.formData1 = response.data.sysNetwork1;
        this.loading = false;
      }).catch(error => {
        this.$modal.alertError("加载直播板卡1网络配置数据失败，请稍后重试");
        console.error("getList 报错：", error);
      })
      .finally(() => {
        // 关闭弹框
        this.loadingInstance.close();
        this.loadingInstance = null;
      });
    },
    getList2() {

      this.loadingInstance = this.$loading({
        lock: true,
        text: '正在加载直播板卡2网络配置数据，请等待',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      this.loading = true;
      listSqlNetwork().then(response => {
        this.formData2 = response.data.sysNetwork2;
        this.loading = false;
      }).catch(error => {
        this.$modal.alertError("加载直播板卡2网络配置数据失败，请稍后重试");
        console.error("getList 报错：", error);
      })
      .finally(() => {
        // 关闭弹框
        this.loadingInstance.close();
        this.loadingInstance = null;
      });

    },
    submitForm() {
      // if(!this.changeFlag){
      //     this.$modal.alertError("服务器获取地址异常,暂时不允许修改网络配置");
      //     return;
      //   }
      this.loadingInstance = this.$loading({
        lock: true,
        text: '正在修改主控板网络配置，请等待',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      this.$refs['elForm'].validate(valid => {
        if(valid){
          updateNetwork(this.formData).then(response => {
              // this.$modal.msgSuccess("主控版服务器网络配置修改成功");
              console.log(JSON.stringify(response));
              this.$modal.msgSuccess(response.msg);
              this.open = false;
              this.getList();
              // this.getListTotal();
            }).catch(error => {
              this.$modal.alertError("主控版服务器网络配置修改失败，请稍后重试");
              console.error("getList 报错：", error);
            })
            .finally(() => {
              // 关闭弹框
              this.loadingInstance.close();
              this.loadingInstance = null;
            });
        }else{
          return;
        }
      })
    },
    submitForm1() {
        if(!this.changeFlag1){
          this.$modal.alertError("直播网卡1网络连接异常,暂时不允许修改该网络地址");
          return;
        }
      this.loadingInstance = this.$loading({
        lock: true,
        text: '正在修改直播板卡1网络配置，请等待',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$refs['elForm1'].validate(valid => {
        if(valid){
          updateNetwork(this.formData1).then(response => {
              this.$modal.msgSuccess("直播板卡1网络配置修改成功");
              this.open = false;
              this.getList1();
              // this.getListTotal();
            }).catch(error => {
              this.$modal.alertError("直播板卡1网络配置修改失败，请稍后重试");
              console.error("getList 报错：", error);
            })
            .finally(() => {
              // 关闭弹框
              this.loadingInstance.close();
              this.loadingInstance = null;
            });
        }else{
          return;
        }
      })
    },
    submitForm2() {
      if(!this.changeFlag2){
          this.$modal.alertError("直播版卡2网络连接异常,暂时不允许修改该网络地址");
          return;
        }
              this.loadingInstance = this.$loading({
        lock: true,
        text: '正在修改直播板卡2网络配置，请等待',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$refs['elForm2'].validate(valid => {
        if(valid){
          updateNetwork(this.formData2).then(response => {
              this.$modal.msgSuccess("直播板卡2网络配置修改成功");
              this.open = false;
              this.getList2();
              // this.getListTotal();
            }).catch(error => {
              this.$modal.alertError("直播板卡2网络配置修改失败，请稍后重试");
              console.error("getList 报错：", error);
            })
            .finally(() => {
              // 关闭弹框
              this.loadingInstance.close();
              this.loadingInstance = null;
            });
          console.log("表单验证通过");
        }else{
          console.log("表单验证不通过");
          return;
        }
      })
    },
    goTarget(href) {
      window.open(href, "_blank");
    },
    resetForm() {
      this.getList();
    },
    resetForm1() {
      this.getList1();
    },
    resetForm2() {
      this.getList2();
    },

  }
};
</script>

<style scoped lang="scss">
.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }
  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }
  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }
}
</style>

